<?php

namespace app\common\model\mycurrency;

use think\Model;
use traits\model\SoftDelete;

class MerchantProfit extends Model
{

    //use SoftDelete;

    

    // 表名
    protected $name = 'mycurrency_merchant_profit';

    const CHANGE_TYPE_SHANGPU = 1;//收益类型:1=商铺收益变动
    const CHANGE_TYPE_MENDIAN = 2;//收益类型:2=门店收益变动

    /**
     *  门店分成
     * @param int $store_id 门店id
     * @param int $paid_dlready 分成基数
     * @param array $data 扩展数据
    */
    public static function divideInto($store_id,$paid_dlready,$data = []){
        $separated = 0;//已分出比分比【拿着这个参数去对代理业务员进行分成】
        $store = MerchantStore::where(['id' => $store_id,'status' => MerchantStore::STATUS_ZHENGCHENG,'deletetime' => null])->find();
        if($store){
            //生成分成记录
            $separated = $store['divideinto'];
            $actual_income = sprintf("%.2f",($paid_dlready / 100) * $store['divideinto']) ;
            $increase = [
                'change_type' => self::CHANGE_TYPE_MENDIAN,
                'store_id' => $store->id,
                'tra_amount' => $paid_dlready,
                'div_proportion' => $store->divideinto,
                'actual_income' => $actual_income,
                'memo' => '租赁订单收益分成',
                'createtime' => time(),
            ];
            $increase = array_merge($increase,$data);
            $profit = self::create($increase);

            //分成更新到余额
            MerchantMoneyLog::moneyChange(
                MerchantMoneyLog::CHANGE_TYPE_STORE,
                null,
                $store->id,
                $actual_income,
                MerchantMoneyLog::TYPE_YONGHUXIAOFEI,
                [
                    'profit_id' => $profit->id,
                ]
            );
        }
        return $paid_dlready - $actual_income;
    }

    public function getCreatetimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }

    public function store()
    {
        return $this->hasOne(MerchantStore::class, 'id', 'store_id');
    }
}
